""" (4.2) Add resource_availability property to a resource

Revision ID: 4dfd8797fdfa
Revises: 3496c876cd1a
Create Date: 2017-09-27 15:57:27.933008

"""
from alembic import op
import sqlalchemy as sa

from sqlalchemy.dialects import postgresql  # Adding this manually

# revision identifiers, used by Alembic.
revision = '4dfd8797fdfa'
down_revision = '3496c876cd1a'
branch_labels = None
depends_on = None

resource_tables = ['blueprints', 'plugins', 'secrets', 'snapshots', 'events',
                   'executions', 'logs', 'nodes', 'node_instances',
                   'deployments', 'deployment_modifications',
                   'deployment_updates', 'deployment_update_steps']


def upgrade():
    # Adding the enum resource_availability to postgres
    resource_availability = postgresql.ENUM('private', 'tenant', 'global',
                                            name='resource_availability')
    op.execute(postgresql.base.CreateEnumType(resource_availability))

    # Update the resource_availability according to private_resource
    update_query = """UPDATE {0}
                      SET resource_availability = CAST (CASE
                          WHEN (private_resource is true) THEN {1}
                          WHEN (private_resource is false) THEN {2}
                      END AS resource_availability);"""

    # Add the resource_availability column and update its value
    for table_name in resource_tables:
        op.add_column(table_name, sa.Column('resource_availability',
                                            resource_availability,
                                            nullable=True))
        op.execute(update_query.format(
            table_name,
            "'{}'".format('private'),
            "'{}'".format('tenant')
        ))


def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_column('snapshots', 'resource_availability')
    op.drop_column('secrets', 'resource_availability')
    op.drop_column('plugins', 'resource_availability')
    op.drop_column('nodes', 'resource_availability')
    op.drop_column('node_instances', 'resource_availability')
    op.drop_column('logs', 'resource_availability')
    op.drop_column('executions', 'resource_availability')
    op.drop_column('events', 'resource_availability')
    op.drop_column('deployments', 'resource_availability')
    op.drop_column('deployment_updates', 'resource_availability')
    op.drop_column('deployment_update_steps', 'resource_availability')
    op.drop_column('deployment_modifications', 'resource_availability')
    op.drop_column('blueprints', 'resource_availability')
    # ### end Alembic commands ###

    # Removing the enum resource_availability from postgres
    resource_availability = postgresql.ENUM('private', 'tenant', 'global',
                                            name='resource_availability')
    resource_availability.drop(op.get_bind())
